package cn.rui.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.rui.common.ContentBean;
import cn.rui.pojo.vo.PageVo;
import cn.rui.common.ResponseBean;
import cn.rui.mapper.NoticeMapper;
import cn.rui.mapper.UserMapper;
import cn.rui.pojo.Notice;
import cn.rui.pojo.User;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author 徽州大都督
 * @date 2021/6/11
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class NoticeSerivice {

    @Autowired
    private NoticeMapper noticeMapper;
    @Autowired
    private UserMapper userMapper;

    public ResponseBean findPage(PageVo pageVo, HttpSession session) {

        QueryWrapper<Notice> wrapper = new QueryWrapper<> ();
        if (StrUtil.isNotEmpty (pageVo.getQueryContent ())){
            wrapper.like ("title",pageVo.getQueryContent ());
        }
        wrapper.orderByDesc ("create_time");

        Page<Notice> page = new Page<> (pageVo.getCurrentPage (),pageVo.getPageSize ());

        IPage<Notice> noticeIPage = noticeMapper.selectPage (page, wrapper);

        PageVo pv = new PageVo ();

        pv.setTotal (noticeIPage.getTotal ());

        List<Notice> noticeList = noticeIPage.getRecords ();

        if (CollUtil.isNotEmpty (noticeList)){
            for (Notice notice : noticeList) {
                User user = userMapper.selectById (notice.getUserId ());
                notice.setUser (user);
            }
        }

        pv.setData (noticeList);

        return ResponseBean.success (ContentBean.QuerySuccess,pv);
    }

    public ResponseBean save(Notice notice, HttpSession session) {
        String username = (String) session.getAttribute ("username");
        QueryWrapper<User> wrapper = new QueryWrapper<> ();
        wrapper.eq ("username",username);
        User user = userMapper.selectOne (wrapper);
        notice.setUserId (user.getId ());
        noticeMapper.insert (notice);

        return ResponseBean.success (ContentBean.SavaSuccess);
    }

    public ResponseBean deleteById(Integer id) {
        noticeMapper.deleteById (id);
        return ResponseBean.success (ContentBean.DeleteSuccess);
    }
}
